<template>
  <div>
    <div class="vux-demo">
      <img class="logo" src="../assets/vux_logo.png">
      <h1> 登录 </h1>
    </div>
    <form>
      <group>
        <x-input title="账号" placeholder="输入手机号" v-model="username"></x-input>
      </group>
      <group>
        <x-input title="密码" placeholder="输入密码" type="password" v-model="password"></x-input>
      </group>
      <!--<group>-->
        <!--<x-input title="服务" placeholder="输入服务地址" v-model="serverUrl"></x-input>-->
      <!--</group>-->
      <box gap="30px 10px 10px 10px">
        <x-button type="primary" action-type="button" @click.native="doLogin">登录</x-button>
      </box>
      <box gap="10px 10px">
        <x-button type="default" action-type="button">注册</x-button>
      </box>
    </form>
  </div>
</template>

<script>
  import { Group, Cell, Grid, GridItem, XInput, XButton, Box, LoadingPlugin, ToastPlugin, AlertModule } from 'vux'
  import Vue from 'vue'
  Vue.use(LoadingPlugin)
  Vue.use(ToastPlugin)

  export default {
    components: {
      Group,
      Cell,
      Grid,
      GridItem,
      XInput,
      XButton,
      Box,
      AlertModule
    },
    data () {
      return {
        msg: 'Hello World!',
        username: 'super',
        password: 'yd@123456',
        serverUrl: this.$store.state.url
      }
    },
    methods: {
      doLogin () {
        var usernameVal = this.username
        var passwordVal = this.password
        if (Object.is(usernameVal, '')) {
          this.$vux.toast.text('账号不能为空')
          return
        }
        if (Object.is(passwordVal, '')) {
          this.$vux.toast.text('账号密码不能为空')
          return
        }

        this.$vux.loading.show({text: '正在提交'})
        console.debug('username=' + usernameVal)
        var _this2 = this
        this.$axios.post('/sys/login/login', {
          username: usernameVal,
          password: passwordVal
        })
        .then(function (response) {
          _this2.$vux.loading.hide()
          if (response.data.data) {
            _this2.$vux.loading.show({
              text: '登录成功'
            })
            setTimeout(() => {
              _this2.$vux.loading.hide()
              sessionStorage.setItem('api_token', response.data.data)
              // 获取登录成功后要跳转的路由。
              let redirect = decodeURIComponent(_this2.$route.query.redirect || '/')
              console.info(redirect)
              if (!redirect || redirect === '' || redirect === '/') {
                redirect = '/home'
              }
              _this2.$router.push({
                path: redirect
              })
            }, 500)
          } else {
            AlertModule.show({
              type: 'error',
              title: '登录异常',
              content: '没有成功获取到token'
            })
          }
        })
      }
    }
  }
</script>

<style>
  .vux-demo {
    text-align: center;
  }
  .logo {
    width: 100px;
    height: 100px
  }
</style>
